#include <string>
#include <pthread.h>
#include <vector>
#include <queue>
#include "Log.hpp"
#include "Thread.hpp"
#include "Cond.hpp"
#include "Mutex.hpp"

namespace ThraedPoolMoudule
{
    using namespace ThreadModlue;
    using namespace LogMoudle;
    using namespace CondModule;
    using namespace MutexModule;

    static const int gnum = 15; // 缺省线程个数
    template <typename T>
    class ThreadPool
    {
    private:
        // 唤醒所有线程
        void WakeupAllThread()
        {
            LockGuard lockguard(_mutex);

            if (_sleepernum > 0)
            {
                _cond.Broadcast();
                LOG(LogLevel::INFO) << "唤醒所有的休眠线程";
            }
        }

        void WakeUpOne()
        {
            _cond.Signal();
            LOG(LogLevel::INFO) << "唤醒一个休眠线程";
        }

        ThreadPool(int num = gnum) : _num(num), _isrunning(false), _sleepernum(0)
        {
            // std::cout << "ThreadPool 构造函数调用，线程数: " << _num << std::endl;
            for (int i = 0; i < num; i++)
            {
                _threads.emplace_back(
                    [this, i]()
                    {
                        // std::cout << "线程 " << i << " 启动" << std::endl;
                        HandlerTask(); // 回调执行
                        // std::cout << "线程 " << i << " 结束" << std::endl;
                    });
                LOG(LogLevel::INFO) << "create new thread success";
            }
        }

        // 启动所有线程
        void Start()
        {
            if (_isrunning)
                return;
            _isrunning = true;

            for (auto &thread : _threads)
            {
                thread.Start();
                // LOG(LogLevel::INFO) << "start new thread success : " << thread.Name();
            }
        }

        // 单例模式: 禁用拷贝构造和赋值语句
        ThreadPool(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

    public:
        // 获取当前线程的单例
        // 静态化, 没有对象也可以调用
        static ThreadPool<T> *GetInstance()
        {
            if (inc == nullptr) // 双层判断，提高获取单例的效率
            {
                LockGuard lockguard(_lock); // 线程安全版本
                LOG(LogLevel::DEBUG) << "获取单例...";
                if (inc == nullptr)
                { // 没有单例就创建一个单例
                    LOG(LogLevel::DEBUG) << "首次使用单例, 创建之";
                    inc = new ThreadPool<T>();
                    inc->Start();
                }
            }

            return inc;
        }

        void Stop()
        {
            if (!_isrunning)
                return;
            _isrunning = false;

            // 唤醒所有线程
            WakeupAllThread();
        }

        void Join()
        {
            for (auto &thread : _threads)
            {
                thread.Join();
            }
        }

        void HandlerTask()
        {
            char name[128];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                T t;
                // sleep(1);
                // LOG(LogLevel::DEBUG) << name << " is running ";
                {
                    LockGuard LockGuard(_mutex);
                    // 1. a.队列是否为空 b.线程池没有退出-> 才去休眠！
                    while (_taskq.empty() && _isrunning)
                    {
                        _sleepernum++;
                        _cond.Wait(_mutex);
                        _sleepernum--;
                    }
                    // 2. 内部的线程被唤醒
                    if (!_isrunning && _taskq.empty())
                    {
                        LOG(LogLevel::INFO) << name << "退出了，线程池退出&&任务队列为空";
                        break;
                    }
                    // 有任务
                    t = _taskq.front(); // 从q取任务, 任务已经是线程私有的了！
                    _taskq.pop();
                }
                t(); // 处理任务, 不用再临界区内部
            }
        }

        bool Enqueue(const T &in)
        {
            if (_isrunning)
            {
                LockGuard lockguard(_mutex);
                _taskq.push(in);
                if (_threads.size() == _sleepernum)
                    WakeUpOne();
                return true;
            }
            return false;
        }  

        ~ThreadPool()
        {
        }

    private:
        std::vector<Thread> _threads;
        int _num;             // 线程池中线程个数
        std::queue<T> _taskq; // 任务队列
        Cond _cond;
        Mutex _mutex;

        bool _isrunning;
        int _sleepernum;           // 休眠中的线程个数
        static ThreadPool<T> *inc; // 单例指针
        static Mutex _lock;        // 保护单例的锁
    };

    template <typename T>
    ThreadPool<T> *ThreadPool<T>::inc = nullptr; // static变量在类外初始化

    template <typename T>
    Mutex ThreadPool<T>::_lock;
}